package com.cuiweiyou.gimmick;

import java.awt.Color;
import java.awt.Component;
import java.awt.Rectangle;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.DefaultCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

public class GimmickMaster {
    private JTable gimmickTable;

    private DefaultTableModel tableModel;
    private DefaultTableCellRenderer cellRenderer;

    private List<GimmickBean> gimmickList;
    private List<GimmickBean> otherSideGimmickList;

    private int globalIndex = 1;

    private String newGimmickSide = "M";

    private Color ffffccColor = new Color(Integer.valueOf("#ffffcc".substring(1), 16));
    private Color ccffffColor = new Color(Integer.valueOf("#ccffff".substring(1), 16));

    public GimmickMaster(GimmickUI gimmickUI) {
        gimmickUI.setMaster(this);
        tableModel = new DefaultTableModel();
        this.gimmickTable = gimmickUI.getGimmickTable();
        this.gimmickTable.setModel(tableModel);
        gimmickList = new ArrayList<>();
        otherSideGimmickList = new ArrayList<>();
    }

    public void loadGimmicks(String filePath) {
        gimmickList = getGimmickList(filePath);
        otherSideGimmickList.clear();
        updateData(gimmickList); // 加载话术文件更新
    }

    public void saveGimmicks(String filePath) {
        List<String> lines = new ArrayList<>();
        for (int i = 0; i < gimmickList.size(); i++) {
            GimmickBean gimmickBean = gimmickList.get(i);
            String index = gimmickBean.getIndex();
            String gimmick = gimmickBean.getGimmick();
            List<String> othersideIndexList = gimmickBean.getOthersideIndexList();
            String prex = "===" + gimmickBean.getSide();
            String lastIndexs = UtilListOrString.listToString(othersideIndexList);
            String nextIndexs = UtilListOrString.listToString(gimmickBean.getNextIndexList());
            String line = prex + index + Constant.GIMMICK_SPLITE_FLAG +
                    gimmick + Constant.GIMMICK_SPLITE_FLAG +
                    lastIndexs + Constant.GIMMICK_SPLITE_FLAG +
                    nextIndexs;
            lines.add(line);
        }
        UtilFile.saveStringsToTxtFile(filePath, lines);

        clearGimmicks(); // 保存话术后清空
    }

    public void clearOthersideGimmicks() {
        otherSideGimmickList.clear();
    }

    public void setGimmickSide(String side) {
        this.newGimmickSide = side;
    }

    public void addGimmick(String gimmick) {
        GimmickBean newGimmick = new GimmickBean();
        newGimmick.setIndex(globalIndex + "");
        if (otherSideGimmickList.size() > 0) {
            List<String> othersideIndexs = new ArrayList<>();

            othersideLoop:
            for (int i = 0; i < otherSideGimmickList.size(); i++) {
                GimmickBean gimmickOtherside = otherSideGimmickList.get(i);
                String indexOtherSide = gimmickOtherside.getIndex();

                tableLoop:
                for (int j = 0; j < gimmickList.size(); j++) {
                    GimmickBean gimmickTable = gimmickList.get(j);
                    String indexTable = gimmickTable.getIndex();
                    if (indexTable.equals(indexOtherSide)) {
                        List<String> nextIndexList = gimmickTable.getNextIndexList();
                        if (1 == nextIndexList.size() && "-1".equals(nextIndexList.get(0))) {
                            nextIndexList.clear();
                        }
                        if (!nextIndexList.contains(globalIndex + "")) {
                            nextIndexList.add(globalIndex + "");
                            break tableLoop;
                        }
                    }
                }
                othersideIndexs.add(indexOtherSide);
            }
            newGimmick.setOthersideIndexList(othersideIndexs);
        } else {
            newGimmick.setOthersideIndexList(new ArrayList<String>() {
                {
                    add("-1");
                }
            });
        }
        newGimmick.setGimmick(gimmick);
        newGimmick.setNextIndexList(new ArrayList<String>() {
            {
                add("-1");
            }
        });

        newGimmick.setSide(newGimmickSide);

        System.out.println("话术内容：" + newGimmick.toString());
        gimmickList.add(newGimmick);

        globalIndex = globalIndex + 1;

        updateData(gimmickList); // 添加新条目后更新
    }

    public void addGimmickToOtherSide(GimmickBean gimmick, GimmickUI.OnAddTableItemToOthersideListener beLastListener) {
        if (!otherSideGimmickList.contains(gimmick)) {
            otherSideGimmickList.add(gimmick);
            if (null != beLastListener) {
                beLastListener.onAddTableItemToOtherside(gimmick);
            }
        }
    }

    public void removeOtherSideGimmick(String element, GimmickUI.OnListViewItemDeletedListener deletedListener) {
        String[] split = element.split(Constant.OTHERSIDE_SPLITE_FLAG);
        String index = split[0];
        GimmickBean tmp = null;
        for (int i = 0; i < otherSideGimmickList.size(); i++) {
            GimmickBean gimmick = otherSideGimmickList.get(i);
            String gi = gimmick.getIndex();
            if (gi.equals(index)) {
                otherSideGimmickList.remove(gimmick);
                tmp = gimmick;
                break;
            }
        }

        if (null != deletedListener) {
            deletedListener.onListViewItemDeleted(tmp);
        }
    }

    public void removeGimmick(GimmickBean gimmick, GimmickUI.OnTableItemDeletedListener deletedListener) {
        String index = gimmick.getIndex();

        if (gimmickList.contains(gimmick)) {
            gimmickList.remove(gimmick);

            for (int i = 0; i < gimmickList.size(); i++) {
                GimmickBean gimmickBean = gimmickList.get(i);
                List<String> lastIndexList = gimmickBean.getOthersideIndexList();
                if (lastIndexList.contains(index)) {
                    lastIndexList.remove(index);
                }
                if (0 == lastIndexList.size()) {
                    lastIndexList.add("-1");
                }
                List<String> nextIndexList = gimmickBean.getNextIndexList();
                if (nextIndexList.contains(index)) {
                    nextIndexList.remove(index);
                }
                if (0 == nextIndexList.size()) {
                    nextIndexList.add("-1");
                }
            }

            updateData(gimmickList); // 删除条目后更新
        }

        boolean isContainsInOtherSide = false;
        if (otherSideGimmickList.contains(gimmick)) {
            otherSideGimmickList.remove(gimmick);
            isContainsInOtherSide = true;
        }

        if (null != deletedListener) {
            deletedListener.onTableItemDeleted(gimmick, isContainsInOtherSide);
        }
    }

    public void clearGimmicks() {
        tableModel.getDataVector()
                  .clear();
        tableModel.fireTableDataChanged();
        tableModel.setRowCount(0);
        gimmickTable.updateUI();

        newGimmickSide = "M";

        globalIndex = 1;
        gimmickList.clear();
        otherSideGimmickList.clear();
    }

    public List<GimmickBean> getAllGimmicks() {
        return gimmickList;
    }

    public List<GimmickBean> getAllOthersideGimmicks() {
        return otherSideGimmickList;
    }

    public GimmickBean findGimmick(GimmickBean gb) {
        if (gimmickList.contains(gb)) {
            int index = gimmickList.indexOf(gb);
            GimmickBean gimmickBean = gimmickList.get(index);
            return gimmickBean;
        }

        return null;
    }

    public void updateData() {
        updateData(gimmickList); // 再次编辑后更新
    }

    private void updateData(List<GimmickBean> list) {
        tableModel.getDataVector()
                  .removeAllElements();

        String[] heads = {"编号", "话术", "上一句", "下一句", "所属"};

        int size = list.size();

        String[][] deviceData = new String[size][5];
        for (int i = 0; i < size; i++) {
            GimmickBean bean = list.get(i);
            String index = bean.getIndex();
            String gimmick = bean.getGimmick();
            String lastIndexs = UtilListOrString.listToString(bean.getOthersideIndexList());
            String nextIndexs = UtilListOrString.listToString(bean.getNextIndexList());
            String side = bean.getSide();

            String[] device = {index, gimmick, lastIndexs, nextIndexs, side};
            deviceData[i] = device;
        }

        tableModel.setDataVector(deviceData, heads);

        int columnCount = gimmickTable.getColumnCount();
        int tableWidth = gimmickTable.getWidth();
        int columnIndex1Width = 45;
        int columnIndex2Width = tableWidth / 5 * 2;
        int columnIndex3Width = tableWidth / 5 * 1;
        int columnIndex4Width = tableWidth / 5 * 1;
        int columnIndex5Width = 45;
        TableColumnModel columnModel = gimmickTable.getColumnModel();
        columnModel.getColumn(columnCount - 1)
                   .setCellEditor(new DefaultCellEditor(new JCheckBox()));
        for (int i = 0; i < columnCount; i++) {
            TableColumn column = columnModel.getColumn(i);
            if (0 == i) {
                column.setPreferredWidth(columnIndex1Width);
            } else if (i == 1) {
                column.setPreferredWidth(columnIndex2Width);
            } else if (i == 2) {
                column.setPreferredWidth(columnIndex3Width);
            } else if (i == 3) {
                column.setPreferredWidth(columnIndex4Width);
            } else {
                column.setPreferredWidth(columnIndex5Width);
            }

            column.setCellRenderer(getTableCellRenderer());
        }

        gimmickTable.updateUI();

        int rowCount = gimmickTable.getRowCount();
        gimmickTable.getSelectionModel()
                    .setSelectionInterval(rowCount - 1, rowCount - 1);
        Rectangle rect = gimmickTable.getCellRect(rowCount - 1, 0, true);
        gimmickTable.scrollRectToVisible(rect);
    }

    private DefaultTableCellRenderer getTableCellRenderer() {
        if (null != cellRenderer) {
            return cellRenderer;
        }

        cellRenderer = new DefaultTableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                int columnCount = table.getColumnCount();
                table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
                if (row % 2 == 0) {
                    setBackground(ffffccColor);
                } else if (row % 2 == 1) {
                    setBackground(ccffffColor);
                }

                if (column == 0 || column == (columnCount - 1)) {
                    setHorizontalAlignment(SwingConstants.CENTER);
                } else {
                    setHorizontalAlignment(SwingConstants.LEFT);
                }

                return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            }
        };

        return cellRenderer;
    }

    private List<GimmickBean> getGimmickList(String filePath) {
        List<GimmickBean> result = new ArrayList<>();

        BufferedReader reader = null;
        StringBuilder sb = new StringBuilder();
        try {
            reader = new BufferedReader(new FileReader(filePath));
            String line;
            while (null != (line = reader.readLine())) {
                System.out.println("读取话术：" + line);

                if (line.startsWith("===")) { // 新的一句
                    if (sb.length() > 0) { // 之前的一句
                        String s = sb.toString();

                        String[] split = s.split(Constant.GIMMICK_SPLITE_FLAG);
                        String index = split[0].replace("===", "");
                        String side = "other";
                        if (index.startsWith("M")) { // 回复，me
                            side = "me";
                            index = index.replaceFirst("M", "");
                        } else if (index.startsWith("O")) { // 对方的话，other
                            side = "other";
                            index = index.replaceFirst("O", "");
                        }
                        String text = split[1];
                        List<String> last = UtilListOrString.stringToList(split[2]);
                        List<String> next = UtilListOrString.stringToList(split[3]);
                        result.add(new GimmickBean(index, text, last, next, side));
                        sb.delete(0, sb.length());
                    }
                }
                sb.append(line + System.getProperty("line.separator"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        if (sb.length() > 0) {
            String s = sb.toString();

            String[] split = s.split(Constant.GIMMICK_SPLITE_FLAG);
            String index = split[0].replace("===", "");
            String side = "O";
            if (index.startsWith("M")) { // 回复，me
                side = "M";
                index = index.replaceFirst("M", "");
            } else if (index.startsWith("O")) { // 对方的话，other
                side = "O";
                index = index.replaceFirst("O", "");
            }
            String text = split[1];
            List<String> last = UtilListOrString.stringToList(split[2]);
            List<String> next = UtilListOrString.stringToList(split[3]);
            result.add(new GimmickBean(index, text, last, next, side));
            sb.delete(0, sb.length());
        }

        return result;
    }

}
